package com.hsgene.user.controller.groundservant;

import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.basic.SimpleRegexUtils;
import com.hsgene.common.util.basic.SimpleStringUtils;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.OrderHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.user.condition.GeneticTestingUserAddressCondition;
import com.hsgene.user.condition.GroundServantInfoCondition;
import com.hsgene.user.domain.GeneticTestingUserAddress;
import com.hsgene.user.dto.address.AddressDetails;
import com.hsgene.user.dto.address.GeneticTestingUserAddressDetails;
import com.hsgene.user.dto.address.GeneticTestingUserAddressDto;
import com.hsgene.user.dto.address.GroundServantAddressIdsDto;
import com.hsgene.user.dto.user.groundservant.GroundServantInfoDto;
import com.hsgene.user.exception.GeneticTestingUserAddressErrorCode;
import com.hsgene.user.exception.UserErrorCode;
import com.hsgene.user.service.GeneticTestingUserAddressService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 地址收货地址管理类
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.user.controller.groundservant
 * @author: maodi
 * @createDate: 2018/11/8 9:03
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/ground/servant")
public class GeneticTestingUserAddressController {

    private static Logger LOGGER = LogManager.getLogger(GeneticTestingUserAddressController.class);

    @Resource
    private GeneticTestingUserAddressService geneticTestingUserAddressService;

    /**
     * @param
     * @return com.hsgene.common.util.result.ApiResult<java.util.List < java.util.Map < java.lang.String , java.lang
     * .Object>>>
     * @description 获取地服下拉框数据源
     * @author maodi
     * @createDate 2018/11/8 16:51
     */
    @GetMapping("select")
    public ApiResult<List<Map<String, Object>>> selectGroundServants() {
        try {
            return ApiResult.succ(geneticTestingUserAddressService.selectGroundServant());
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserAddressErrorCode.SELECT_GROUND_SERVANT_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserAddressErrorCode.SELECT_GROUND_SERVANT_IS_ERROR);
        }
    }

    /**
     * @param condition
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.support.Pagination < com.hsgene.user.dto
     * . address.GeneticTestingUserAddressDto>>
     * @description 地服收货地址列表/查询地服收货地址列表
     * @author maodi
     * @createDate 2018/11/9 13:28
     */
    @GetMapping("addresses")
    public ApiResult<Pagination<GeneticTestingUserAddressDto>> queryAddresses(GeneticTestingUserAddressCondition
                                                                                      condition) {
        try {
            Integer page = condition.getPage();
            if (page == null) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(page.toString())) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NOT_POSITIVE_INTEGER);
            }
            Integer size = condition.getSize();
            if (size == null) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(size.toString())) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NOT_POSITIVE_INTEGER);
            }
            String sort = condition.getSort();
            if (StringUtils.isBlank(sort)) {
                sort = "desc";
            }
            sort = sort.toLowerCase();
            if (StringUtils.isNotBlank(sort)) {
                if (!"desc".equalsIgnoreCase(sort) && !"asc".equalsIgnoreCase(sort)) {
                    return ApiResult.fail(CommonErrorCode.SORT_ORDER_IS_ERROR);
                }
            }
            String groundServantTerritory = condition.getGroundServantTerritory();
            if (StringUtils.isNotBlank(groundServantTerritory)) {
                int territoryCount = geneticTestingUserAddressService.queryCountSysDictByTerritoryName
                        (groundServantTerritory);
                if (territoryCount < 1) {
                    return ApiResult.fail(GeneticTestingUserAddressErrorCode.GROUND_SERVANT_TERRITORY_NAME_IS_ERROR);
                }
            }
            String groundServantProvince = condition.getGroundServantProvince();
            if (StringUtils.isNotBlank(groundServantProvince)) {
                int provinceCount = geneticTestingUserAddressService.queryCountSysAreaByName(groundServantProvince);
                if (provinceCount < 1) {
                    return ApiResult.fail(GeneticTestingUserAddressErrorCode.GROUND_SERVANT_PROVINCE_NAME_IS_ERROR);
                }
            }
            int totalCount = geneticTestingUserAddressService.queryGroundServantCountByCondition(condition);
            LimitHelper limitHelper = LimitHelper.create(page, size, true);
            condition.setLimitHelper(limitHelper);
            OrderHelper orderHelper = OrderHelper.create("b.update_date_time", sort);
            condition.setOrderHelper(orderHelper);
            List<GeneticTestingUserAddressDto> result = geneticTestingUserAddressService.queryGroundServantByCondition
                    (condition);
            addNum(result, page, size);
            Pagination pagination = Pagination.newInstance(limitHelper, totalCount, result);
            return ApiResult.succ(pagination);
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserAddressErrorCode.QUERY_GROUND_SERVANT_ADDRESS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserAddressErrorCode.QUERY_GROUND_SERVANT_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param userId 用户id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.user.dto.address.GeneticTestingUserAddressDetails>
     * @description 根据用户id获取地服收货地址详细信息
     * @author maodi
     * @createDate 2018/11/9 13:40
     */
    @GetMapping("addresses/details/{user_id}")
    public ApiResult<GeneticTestingUserAddressDetails> queryAddressDetails(@PathVariable("user_id") String userId) {
        try {
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.DETAILS_GROUND_SERVANT_USER_ID_IS_NOT_NULL);
            }
            List<AddressDetails> addressDetails = geneticTestingUserAddressService.queryAddressDetails(userId);
            GeneticTestingUserAddressDetails details = geneticTestingUserAddressService.queryGroundServantBaseInfo
                    (userId);
            if (details == null) {
                details = new GeneticTestingUserAddressDetails();
            }
            details.setAddresses(addressDetails);
            return ApiResult.succ(details);
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserAddressErrorCode.QUERY_GROUND_SERVANT_ADDRESS_DETAILS_IS_ERROR.getMessage
                    (), e);
            return ApiResult.fail(GeneticTestingUserAddressErrorCode.QUERY_GROUND_SERVANT_ADDRESS_DETAILS_IS_ERROR);
        }
    }

    /**
     * @param details 地服收货地址信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 新增地服收货地址
     * @author maodi
     * @createDate 2018/11/9 15:05
     */
    @PostMapping("addresses")
    public ApiResult<NullObject> insertGroundServantAddress(@RequestBody GeneticTestingUserAddressDetails details) {
        try {
            ErrorCode code = checkGeneticTestingUserAddress(details, false);
            if (code != null) {
                return ApiResult.fail(code);
            }
            List<AddressDetails> addressDetailsList = details.getAddresses();
            String userId = details.getUserId();
            int userCount = geneticTestingUserAddressService.queryIdsByUserId(userId).size();
            if (userCount > 0) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.GROUND_SERVANT_ADDRESS_IS_EXIST_TO_UPDATE);
            }
            int queryCount = geneticTestingUserAddressService.queryGroundServantByUserId(userId).size();
            if (queryCount >= 5) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.CURRENT_GROUND_SERVANT_ADDRESS_UP_TO_5);
            }
            int currentSize = addressDetailsList.size();
            int afterInsertCount = currentSize + queryCount;
            if (afterInsertCount > 5) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.AFTER_INSERT_GROUND_SERVANT_ADDRESS_UP_TO_5);
            }
            List<GeneticTestingUserAddress> list = copyDetailsToAddress(details);
            geneticTestingUserAddressService.insertGroundServant(list, userId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserAddressErrorCode.INSERT_GROUND_SERVANT_ADDRESS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserAddressErrorCode.INSERT_GROUND_SERVANT_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param details 地服收货地址信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 修改地服收货地址信息
     * @author maodi
     * @createDate 2018/11/9 15:24
     */
    @PutMapping("addresses")
    public ApiResult<NullObject> updateGroundServantAddress(@RequestBody GeneticTestingUserAddressDetails details) {
        try {
            ErrorCode code = checkGeneticTestingUserAddress(details, false);
            if (code != null) {
                return ApiResult.fail(code);
            }
            String userId = details.getUserId();
            int currentSize = details.getAddresses().size();
            if (currentSize > 5) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.AFTER_INSERT_GROUND_SERVANT_ADDRESS_UP_TO_5);
            }
            List<GeneticTestingUserAddress> list = copyDetailsToAddress(details);
            geneticTestingUserAddressService.updateGroundServant(list, userId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserAddressErrorCode.UPDATE_GROUND_SERVANT_ADDRESS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserAddressErrorCode.UPDATE_GROUND_SERVANT_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param groundServantAddressIdsDto 用户id数组字符串实体
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 根据用户id的数组批量删除地服收货地址
     * @author maodi
     * @createDate 2018/11/9 16:45
     */
    @DeleteMapping("addresses")
    public ApiResult<NullObject> deleteGroundServantAddress(@RequestBody GroundServantAddressIdsDto
                                                                    groundServantAddressIdsDto) {
        try {
            String userIdsStr = groundServantAddressIdsDto.getUserIds();
            if (StringUtils.isBlank(userIdsStr)) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.USER_IDS_IS_NOT_NULL);
            }
            String[] userIds = userIdsStr.split(",");
            if (userIds == null) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.USER_IDS_IS_NOT_NULL);
            }
            int queryCount = geneticTestingUserAddressService.queryCountByUserIds(userIds);
            if (queryCount != userIds.length) {
                return ApiResult.fail(GeneticTestingUserAddressErrorCode.SOME_USER_ID_IS_NOT_EXIST);
            }
            geneticTestingUserAddressService.deleteGroundServantMulti(userIds);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserAddressErrorCode.DELETE_GROUND_SERVANT_ADDRESS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserAddressErrorCode.DELETE_GROUND_SERVANT_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param list 公司列表
     * @param page 页数
     * @param size 每页数量
     * @return void
     * @description 为地服收货地址列表添加序号
     * @author maodi
     * @createDate 2018/11/8 10:30
     */
    private void addNum(List<GeneticTestingUserAddressDto> list, int page, int size) {
        int start = (page - 1) * size + 1;
        for (GeneticTestingUserAddressDto dto : list) {
            dto.setNum(start++);
        }
    }

    /**
     * @param details 地服收货地址详情
     * @param checkId 是否校验地服收货地址id
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 检验地服收货地址
     * @author maodi
     * @createDate 2018/11/12 9:51
     */
    private ErrorCode checkGeneticTestingUserAddress(GeneticTestingUserAddressDetails details, Boolean checkId) {
        String userId = details.getUserId();
        if (StringUtils.isBlank(userId)) {
            return CommonErrorCode.USER_ID_IS_NULL;
        }
        String groundServantName = details.getGroundServantName();
        if (StringUtils.isBlank(groundServantName)) {
            return GeneticTestingUserAddressErrorCode.GROUND_SERVANT_NAME_IS_NOT_NULL;
        }
        int queryCount = geneticTestingUserAddressService.queryGeneticTestingUserCountByRealName(groundServantName);
        if (queryCount < 1) {
            return GeneticTestingUserAddressErrorCode.GROUND_SERVANT_NAME_IS_NOT_EXIST;
        }
        int equalCount = geneticTestingUserAddressService.queryGeneticTestingUserCountByUserIdAndRealName(userId,
                groundServantName);
        if (equalCount < 1) {
            return GeneticTestingUserAddressErrorCode.USER_ID_NOT_EQUAL_GROUND_SERVANT_NAME;
        }
        String groundServantTerritory = details.getGroundServantTerritory();
        if (StringUtils.isBlank(groundServantTerritory)) {
            return GeneticTestingUserAddressErrorCode.GROUND_SERVANT_TERRITORY_NAME_IS_NOT_NULL;
        }
        int groundServantTerritoryCount = geneticTestingUserAddressService.queryCountSysDictByTerritoryName
                (groundServantTerritory);
        if (groundServantTerritoryCount < 1) {
            return GeneticTestingUserAddressErrorCode.GROUND_SERVANT_TERRITORY_NAME_IS_ERROR;
        }
        String groundServantProvince = details.getGroundServantOnlyProvince();
        if (StringUtils.isBlank(groundServantProvince)) {
            groundServantProvince = details.getGroundServantProvince();
        }
        if (StringUtils.isBlank(groundServantProvince)) {
            return GeneticTestingUserAddressErrorCode.GROUND_SERVANT_PROVINCE_NAME_IS_NOT_NULL;
        }
        int groundServantProvinceCount = geneticTestingUserAddressService.queryCountSysAreaByName
                (groundServantProvince);
        if (groundServantProvinceCount < 1) {
            return GeneticTestingUserAddressErrorCode.GROUND_SERVANT_PROVINCE_NAME_IS_ERROR;
        }
        List<AddressDetails> list = details.getAddresses();
        if (list == null || list.size() < 1) {
            return GeneticTestingUserAddressErrorCode.ADDRESS_DETAILS_IS_NOT_NULL;
        }
        int defaultCount = 0;
        for (AddressDetails detail : list) {
            if (checkId) {
                String id = detail.getId();
                if (StringUtils.isBlank(id)) {
                    return GeneticTestingUserAddressErrorCode.ADDRESS_DETAILS_ID_IS_NOT_NULL;
                } else {
                    int count = geneticTestingUserAddressService.queryGroundServantById(id).size();
                    if (count < 1) {
                        return GeneticTestingUserAddressErrorCode.ADDRESS_DETAILS_ID_IS_NOT_EXIST;
                    } else if (count > 1) {
                        return GeneticTestingUserAddressErrorCode.ADDRESS_DETAILS_ID_IS_MULTI;
                    }
                }
            }
            String province = detail.getProvince();
            if (StringUtils.isBlank(province)) {
                return GeneticTestingUserAddressErrorCode.PROVINCE_NAME_IS_NOT_NULL;
            }
            int provinceCount = geneticTestingUserAddressService.queryCountSysAreaByName(province);
            if (provinceCount < 1) {
                return GeneticTestingUserAddressErrorCode.PROVINCE_NAME_IS_ERROR;
            }
            String city = detail.getCity();
            if (StringUtils.isNotBlank(city)) {
                int cityCount = geneticTestingUserAddressService.queryCountSysAreaByName(city);
                if (cityCount < 1) {
                    return GeneticTestingUserAddressErrorCode.CITY_NAME_IS_ERROR;
                }
            }
            String district = detail.getDistrict();
            if (StringUtils.isBlank(district)) {
                return GeneticTestingUserAddressErrorCode.DISTRICT_NAME_IS_NOT_NULL;
            }
            int districtCount = geneticTestingUserAddressService.queryCountSysAreaByName(district);
            if (districtCount < 1) {
                return GeneticTestingUserAddressErrorCode.DISTRICT_NAME_IS_ERROR;
            }
            String address = detail.getAddress();
            if (StringUtils.isBlank(address)) {
                return GeneticTestingUserAddressErrorCode.ADDRESS_IS_NOT_NULL;
            }
            String areaId = detail.getAreaId();
            if (StringUtils.isBlank(areaId)) {
                return GeneticTestingUserAddressErrorCode.AREA_ID_IS_NOT_NULL;
            }
            int areaIdCount = geneticTestingUserAddressService.queryCountSysAreaByAreaId(areaId);
            if (areaIdCount < 1) {
                return GeneticTestingUserAddressErrorCode.AREA_ID_IS_ERROR;
            }
            String consignee = detail.getConsignee();
            if (StringUtils.isBlank(consignee)) {
                return GeneticTestingUserAddressErrorCode.CONSIGNEE_IS_NOT_NULL;
            }
            String consigneePhone = detail.getConsigneePhone();
            if (StringUtils.isBlank(consigneePhone)) {
                return GeneticTestingUserAddressErrorCode.CONSIGNEE_PHONE_IS_NOT_NULL;
            }
            if (!SimpleRegexUtils.isMobile(consigneePhone)) {
                return GeneticTestingUserAddressErrorCode.CONSIGNEE_PHONE_IS_ERROR;
            }
            String zipCode = detail.getZipCode();
            if (StringUtils.isBlank(zipCode)) {
                return GeneticTestingUserAddressErrorCode.ZIP_CODE_ID_IS_NOT_NULL;
            }
            if (!SimpleStringUtils.isNumber(zipCode)) {
                return GeneticTestingUserAddressErrorCode.ZIP_CODE_ID_IS_ERROR;
            }
            Integer isDefaultAddress = detail.getIsDefault();
            if (isDefaultAddress == null) {
                return GeneticTestingUserAddressErrorCode.IS_DEFAULT_ADDRESS_ID_IS_NOT_NULL;
            }
            if (isDefaultAddress != 0 && isDefaultAddress != 1) {
                return GeneticTestingUserAddressErrorCode.IS_DEFAULT_ADDRESS_ID_IS_ERROR;
            }
            String remarks = detail.getRemarks();
            if (StringUtils.isNotBlank(remarks)) {
                if (remarks.length() > 200) {
                    return GeneticTestingUserAddressErrorCode.REMARKS_IS_EXCEED_200;
                }
            }
            defaultCount += detail.getIsDefault();
            if (defaultCount > 1) {
                return GeneticTestingUserAddressErrorCode.GROUND_SERVANT_CAN_NOT_HAVE_MULTI_DEFAULT;
            }
            Date date = new Date();
            detail.setUpdateDateTime(date);
            detail.setAddressType(1);
            detail.setFullName(province + city + district + address);
        }
        return null;
    }

    /**
     * @param details 数据地址详情
     * @return java.util.List<com.hsgene.user.domain.GeneticTestingUserAddress>
     * @description 组装复制新增和修改数据
     * @author maodi
     * @createDate 2018/11/9 15:00
     */
    private List<GeneticTestingUserAddress> copyDetailsToAddress(GeneticTestingUserAddressDetails details) {
        String userId = details.getUserId();
        String groundServantName = details.getGroundServantName();
        String groundServantPhone = details.getGroundServantPhone();
        String groundServantTerritory = details.getGroundServantTerritory();
        String groundServantProvince = details.getGroundServantOnlyProvince();
        if (StringUtils.isBlank(groundServantProvince)) {
            groundServantProvince = details.getGroundServantProvince();
        }
        List<AddressDetails> list = details.getAddresses();
        List<GeneticTestingUserAddress> addresses = new ArrayList<>();
        for (AddressDetails detail : list) {
            String id = detail.getId();
            GeneticTestingUserAddress address = new GeneticTestingUserAddress();
            address.setId(id);
            address.setUserId(userId);
            address.setGroundServantName(groundServantName);
            address.setGroundServantPhone(groundServantPhone);
            address.setGroundServantTerritory(groundServantTerritory);
            address.setGroundServantProvince(groundServantProvince);
            address.setProvince(detail.getProvince());
            address.setCity(detail.getCity());
            address.setDistrict(detail.getDistrict());
            address.setAddress(detail.getAddress());
            address.setAreaName(detail.getFullName());
            address.setAreaId(detail.getAreaId());
            address.setConsignee(detail.getConsignee());
            address.setConsigneePhone(detail.getConsigneePhone());
            address.setZipCode(detail.getZipCode());
            address.setIsDefaultAddress(detail.getIsDefault());
            Date date = new Date();
            address.setCreateDateTime(date);
            address.setUpdateDateTime(date);
            address.setRemarks(detail.getRemarks());
            address.setAddressType(detail.getAddressType());
            addresses.add(address);
        }
        return addresses;
    }

    /**
     * 查询指定地址id的地址信息
     *
     * @param addressId 地址id
     * @return 地址信息
     * @author wangbing
     */
    @GetMapping("addresses/{address_id}")
    public ApiResult<GeneticTestingUserAddress> findAddressInfo(
            @PathVariable("address_id") String addressId) {
        try {
            List<GeneticTestingUserAddress> addresses = geneticTestingUserAddressService.queryGroundServantById
                    (addressId);
            if (CollectionUtils.isEmpty(addresses) || addresses.size() < 1) {
                return ApiResult.fail(UserErrorCode.CONSIGN_ADDRESS_NOT_EXISTED);
            }
            return ApiResult.succ(addresses.get(0));
        } catch (Exception e) {
            LOGGER.error(UserErrorCode.FIND_ADDRESS_INFO_BY_ID_IS_ERROR, e);
            return ApiResult.fail(UserErrorCode.FIND_ADDRESS_INFO_BY_ID_IS_ERROR);
        }
    }

    /**
     * @param condition 查询条件
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.support.Pagination<com.hsgene.user.dto
     * .user.groundservant.GroundServantInfoDto>>
     * @description 根据查询条件获取地服信息
     * @author maodi
     * @createDate 2018/11/21 11:49
     */
    @GetMapping
    public ApiResult<Pagination<GroundServantInfoDto>> getGroundServants(GroundServantInfoCondition condition) {
        try {
            Integer page = condition.getPage();
            if (page == null) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(page.toString())) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NOT_POSITIVE_INTEGER);
            }
            Integer size = condition.getSize();
            if (size == null) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(size.toString())) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NOT_POSITIVE_INTEGER);
            }
            condition.setOrderHelper(OrderHelper.create("a.update_date_time", "desc"));
            LimitHelper limitHelper = LimitHelper.create(page, size);
            condition.setLimitHelper(limitHelper);
            List<GroundServantInfoDto> result = geneticTestingUserAddressService.queryGroundServantInfoByCondition
                    (condition);
            int start = (page - 1) * size + 1;
            for (GroundServantInfoDto dto : result) {
                String parentIds = dto.getParentIds();
                int index = -1;
                if (StringUtils.isNotBlank(parentIds)) {
                    index = parentIds.indexOf(",") + 1;
                }
                String topParent = "";
                if (StringUtils.isNotBlank(parentIds) && parentIds.length() > 1 && index != -1) {
                    int secondIndex = parentIds.indexOf(",", index);
                    if (secondIndex != -1) {
                        String topId = parentIds.substring(index, secondIndex);
                        if (StringUtils.isNotBlank(topId)) {
                            topParent = geneticTestingUserAddressService.queryNameByAreaId(topId);
                        }
                    }
                }
                dto.setTopParent(topParent);
                String province = dto.getProvince();
                if (StringUtils.isNotBlank(province)) {
                    int index1 = province.indexOf("省");
                    int index2 = province.indexOf("自治区");
                    int index3 = province.indexOf("特别行政区");
                    int index4 = province.indexOf("北京市");
                    int index5 = province.indexOf("天津市");
                    int index6 = province.indexOf("上海市");
                    int index7 = province.indexOf("重庆市");
                    if (index1 != -1) {
                        province = province.substring(0, index1 + 1);
                    } else if (index2 != -1) {
                        province = province.substring(0, index2 + 3);
                    } else if (index3 != -1) {
                        province = province.substring(0, index3 + 5);
                    } else if (index4 != -1 || index5 != -1 || index6 != -1 || index7 != -1) {
                        province = province.substring(0, 3);
                    }
                    dto.setProvince(province);
                }
                dto.setNum(start++);
            }
            int totalCount = geneticTestingUserAddressService.queryGroundServantInfoCountByCondition(condition);
            Pagination pagination = Pagination.newInstance(limitHelper, totalCount, result);
            return ApiResult.succ(pagination);
        } catch (Exception e) {
            LOGGER.error(UserErrorCode.QUERY_GROUND_SERVANT_INFO_IS_ERROR, e);
            return ApiResult.fail(UserErrorCode.QUERY_GROUND_SERVANT_INFO_IS_ERROR);
        }
    }

}
